package com.ruoyi.common.translate;

import com.ruoyi.common.translate.constant.Translate;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 名称提供者接口
 */
@Slf4j
public abstract class NameProvider<T> {

    // 本地缓存，避免频繁查询数据库
    private final Map<Object, String> localCache = new HashMap<>();

//    @Autowired
//    private RedisCache redisCache;

    protected String baseKey = Translate.NAME + ":" + getType() + ":";

    /**
     * 根据key查询单条数据
     *
     * @param key
     * @return
     */
    public abstract T findEntity(String key);

    /**
     * 根据keys查询多条数据
     *
     * @param keys
     * @return
     */
    public abstract List<T> findEntityList(List<String> keys);

    /**
     * 映射名称
     *
     * @param one
     * @return
     */
    public abstract Map<String, String> mapName(T one);


    public String fetchNameByKey(String id) {
        String key = baseKey;

        // 先从本地缓存获取
/*
*/
//        String cachedName = localCache.get(id);
//        if (cachedName != null) {
//            log.info("从缓存中获取数据：" + cachedName);
//            return cachedName;
//        }

        Map<String, String> map = null;
        T one = findEntity(id);

        if (one != null) {
            map = mapName(one);
        }

        // 放入缓存
//        localCache.putAll(map);
        return map.get(id);
    }

    public Map<String, String> fetchNamesByKeys(List<String> ids) {
        Map<String, String> result = new HashMap<>();

        // 先检查本地缓存
        List<String> uncachedIds = new ArrayList<>();
        for (String id : ids) {
//            String cachedName = localCache.get(id);
//            if (cachedName != null) {
//                result.put(id, cachedName);
//                log.info("从缓存中获取数据：" + cachedName);
//            } else {
                uncachedIds.add(id);
//            }
        }

        // 批量查询未缓存的数据
        if (!uncachedIds.isEmpty()) {
            List<T> list = findEntityList(uncachedIds);
            for (T obj : list) {
                if (obj != null) {
                    Map<String, String> s = mapName(obj);
                    result.putAll(s);
//                    localCache.putAll(s);
                }
            }

        }

        return result;
    }


    /// 获取提供者类型
    public abstract String getType();


    /// 预加载数据
    public void preload(List<String> ids) {
        fetchNamesByKeys(ids);
    }


    private static final Long ERROR_ID = -1L;

    /**
     * 转换 id 类型为 Long
     *
     * @param id
     * @return
     */
    public Long changeIdType(String id) {
        long userId;
        id = id.replace(baseKey, "");

        try {
            userId = Long.parseLong(id);
        } catch (Exception e) {
            userId = ERROR_ID;
        }
        return userId;
    }


}